package it.uniroma2.structure.deploy;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;

public class Deploy {
	private final String namespaceOde = "http://www.apache.org/ode/schemas/dd/2007/03";
	private final String qname = "xmlns";
	private final String deployTag = "deploy";
	private final static String openTag = "<";
	private final String lineXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
//	private final static String closeTag = "/>";
	private static final String processTag = "process";
	private String nameBPEL;
	private String namespaceClient;
	private Hashtable<String, String> coupleNamespace;
	private Provide provide;
	private Vector<Invoke> invokeVec;
	
	
	private Deploy(){
		this.coupleNamespace = new Hashtable<String, String>();
//		this.coupleNamespace.put(this.namespaceOde, this.qname);
		this.invokeVec = new Vector<Invoke>();
	}
	
	
	public Deploy(String name, String namespace){
		this();
		this.nameBPEL = name;
		this.namespaceClient = namespace;
		this.addNamespace(namespace);
		this.provide = new Provide(namespace, name);
	}
	
	
	public void setNamespaces(Hashtable<String, String> couple){
		this.coupleNamespace = couple;
	}
	
	
	public void addNamespace(String uri){
		String value = uri.split("http://")[1];
		this.coupleNamespace.put(uri, value);
	}
	
	
	public void addNamespace(String qname, String uri){
		this.coupleNamespace.put(uri, qname);
	}
	
	
	public String generateDeploy(){
		String output = this.lineXML + "\n";
		
		output = output + generateTagDeploy();
		
		return output;
	}

	
	public void addInvoke(String partnerLink, String namespace, String nameService, String port){
		if(!namespace.equals(this.namespaceClient)){
			this.invokeVec.addElement(new Invoke(partnerLink, namespace, nameService, port));
			this.addNamespace(namespace);
		}
		
	}
	
	
	private String generateTagDeploy() {
		String output = Deploy.openTag + this.deployTag + " ";
		
		output = output + this.qname + "=\"" + this.namespaceOde + "\" ";
		Iterator<String> iter = this.coupleNamespace.keySet().iterator();
		while(iter.hasNext()){
			String key = iter.next();
			String val = this.coupleNamespace.get(key);
			output = output + this.qname + ":" + val + "=\"" + key + "\" ";
		}
		output = output + ">\n";
		
		
		output = output + this.openTag + this.processTag + " name=\"" + this.coupleNamespace.get(this.namespaceClient) + ":" + this.nameBPEL + "\">\n";
		
		output = output + "<active>true</active>\n" +
				"<retired>false</retired>\n" +
				"<process-events generate=\"all\"/>\n";
		
		output = output + this.provide.generateProvide();
		
		
		for(Invoke tempInvoke : this.invokeVec){
			output = output + tempInvoke.generateInvoke();
		}
		
		output = output + "</" + this.processTag + ">\n";
		
		output = output + "</" + this.deployTag + ">\n";
		
		return output;
	}
}
